package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


import com.google.gson.Gson;
import com.model.User;
import com.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/user")
public class UserinfoController {

	@Autowired
	private UserServiceImpl userService;
	
	/**
	 * 获取所有用户列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/getAllUser")
	@ResponseBody
	public List<User> getAllUser(HttpServletRequest request){
		
		List<User> findAll = userService.findAll();
//		Gson gson=new Gson();
//		String a=gson.toJson(findAll);
//		System.out.print(a);
//		request.setAttribute("userList", findAll);
		return findAll;
	}
	
	/**
	 * 跳转到添加用户界面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddUser")
	public String toAddUser(HttpServletRequest request){
		
		return "/addUser";
	}
	/**
	 * 添加用户并重定向
	 * @param request
	 * @return
	 */
	@RequestMapping("/addUser")
	public String addUser(HttpServletRequest request){
		User  user=new User();
		user.setAge("20");
		user.setUserName("maoxiong");
		userService.save(user);
		return "index";
	}
	
	/**
	 *编辑用户
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateUser")
	@ResponseBody
	public String updateUser(HttpServletRequest request){
		//查找一个具体的对象 我们来update
		int id=1;
		User  user=userService.findById(id);
		user.setUserName("testforUpdate");
		user.setAge("34");
		return  userService.update(user)==true?"update cg":"update failed";
	}
	/**
	 * 根据id查询单个用户
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUser")
	public String getUser(int id,HttpServletRequest request){
		
		request.setAttribute("user", userService.findById(id));
		return "/editUser";
	}
	/**
	 * 删除用户
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delUser")
	public void delUser(int id,HttpServletRequest request,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		
		if(userService.delete(id)){
			result = "{\"result\":\"success\"}";
		}
		
		response.setContentType("application/json");
		
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	//测试sql复用
	@RequestMapping("/selectForTestSQL")
	@ResponseBody
	public List<Map> selectForTestSQL(){
		List<Map> list=userService.selectForTestSQL();
		System.out.print(Arrays.toString(list.toArray()));
		return list;
	}
	//测试ResultMap
	@RequestMapping("/selectForTestResultMap")
	@ResponseBody
	public List<User> selectForTestResultMap(){
		 return userService.selectForTestResultMap();
	}
}
